package game.util.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

/**
 * A help class used in dealing with remote service.
 * 
 * @author Linzy
 * Create Date: 2009 9 7 17:42:05
 */
public class RemoteServiceUtil {

	
	
	/**
	 * Call a http service according to the specified url.
	 * 
	 * @param servUrl String; The url string of the service.
	 * @return Result string.
	 */
	public static String callHttpService(String servUrl) {
		StringBuffer result = new StringBuffer();
		try {
			URL url = new URL(servUrl);
			BufferedReader bf = new BufferedReader(
									new InputStreamReader(url.openStream()));
			String strLine = "";
			while ((strLine = bf.readLine()) != null) {
				result.append(strLine.trim());
			}

			bf.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return result.toString();
	} // callHttpService()
	
	/**
	 * Call the http service by a post way.
	 *  
	 * @param serviceUrl String; The service url.
	 * @param postData	String; The data to be posted.
	 * @return The remote service's call result xml String;
	 */
	public static String callServiceByPost(String serviceUrl, String postData) {
		String enc = "utf-8";
		StringBuffer result = new StringBuffer();
		
		OutputStreamWriter outWriter = null;
		BufferedReader reader = null;
		try {
			// Construct data
			StringBuffer encodedData = new StringBuffer();
			String[] postDataLst = postData.split("&");
			for(int i = 0; i < postDataLst.length; i++){
				String param = postDataLst[i];
				int index = param.indexOf("=");
				String name = param.substring(0, index);
				String val = param.substring(index + 1, param.length());
				if(i > 0){
					encodedData.append("&");
				}
				encodedData.append(URLEncoder.encode(name, enc)).append("=");
				encodedData.append(URLEncoder.encode(val, enc));
			} // for()
			
	        // Send data
	        URL url = new URL(serviceUrl);
	        
	        URLConnection conn = url.openConnection();
	        conn.setDoOutput(true);
	        
	        outWriter = new OutputStreamWriter(conn.getOutputStream());
	        outWriter.write(encodedData.toString());
	        outWriter.flush();
	        
	        // Get the response
	        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
	        String line;
	        while ((line = reader.readLine()) != null) {
	        	result.append(line);
	        }

	        outWriter.close();
	        reader.close();
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
		return result.toString();
	} // callServiceByPost()
	
} // end of class
